const baseUrl = 'https://pinggu.mkcom.cn/grade-evaluation-api' // 测试
export {
	baseUrl
}

export function HTTP(options) {
	let isLastReq = options.data?.isLastReq == undefined ? true : false
	uni.showLoading({
		title: '请求数据中',
		mask: true
	})
	return new Promise((resolve, reject) => {
		let token = uni.getStorageSync('access_token');
		// let routes = getCurrentPages();
		// if(!token && routes[routes.length - 1].route != ('pages/login/index' || 'pages/login/binding')) {
		// 	uni.navigateTo({
		// 		url: "/pages/login/index"
		// 	})
		// }
		let header = {}
		if (token) {
			header = {
				'Content-Type': 'application/json',
				'Authorization': token ? 'Bearer ' + token : ''
			}
		} else {
			if (options.url.includes('/auth/oauth/token')) {
				header = {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Authorization': "Basic cGlnOnBpZw=="
				}
			} else {
				header = {
					'content-type': 'application/json',
				}
			}

		}
		uni.request({
			url: baseUrl + options.url,
			method: options.method || "POST",
			data: options.data,
			timeout: 10000,
			header,
			success: (res) => {
				if (isLastReq) {
					uni.hideLoading()
				}
				if (res.data.code === 401) {
					uni.showToast({
						title: "登录已过期，请重新登录",
						icon: "none"
					});
					uni.removeStorage({
						key: "access_token"
					})
					uni.removeStorage({
						key: "userInfo"
					})
					setTimeout(() => {
						uni.navigateTo({
							url: `/pages/home/login`,
						});
					}, 1500);
				}
				if (res.data.code == 500) {
					uni.showToast({
						title: res.data.msg || '系统错误，请联系管理员！',
						mask: true,
						icon: 'none'
					})
					resolve(res.data);

				} else {
					resolve(res.data);
				}

			},
			fail: (err) => {
				uni.hideLoading();
				if (err.errMsg === 'request:fail timeout') {
					uni.showToast({
						title: "连接超时，请稍后重试！",
						icon: "none"
					});
				} else {
					uni.showToast({
						title: "系统错误，请联系管理员！",
						icon: "none"
					});
				}
				reject(err);
			}
		})
	})
}

export function uploadFile(path) {
	uni.showLoading({
		title: '上传中',
		mask: true
	})
	return new Promise((resolve, reject) => {
		let token = uni.getStorageSync('access_token');
		if (!token) {
			uni.navigateTo({
				url: "/pages/login/index"
			})
		}
		uni.uploadFile({
			url: baseUrl + '/hklg-business/minio/upload',
			filePath: path,
			name: 'file',
			success: async (uploadFileRes) => {
				uni.hideLoading();
				resolve(uploadFileRes);

			},
			fail: (err) => {
				uni.hideLoading();
				uni.showToast({
					title: err,
					icon: "none"
				});
				reject(err);
			}
		});
	})
}